package com.cskaoyan.market.admin.controller;

import com.cskaoyan.market.admin.service.AdminStorageService;
import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.util.ZhouWenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/admin/storage")
@MultipartConfig
public class AdminStorageController{
    // 持有Service层对象
    @Autowired
    AdminStorageService adminStorageService;
    

    /**
     * 存储对象创建方法
     * @param request 请求
     * @param response 响应
     */
    @PostMapping("/create")
    private void create(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取文件
        Part part = request.getPart("file");
        // 获取文件名并修改，防止重名
        String fileName = part.getSubmittedFileName();
        fileName = UUID.randomUUID().toString() + "_" + fileName;
        // 获取docBase
        String docBase = request.getServletContext().getRealPath("");
        // 设定路径
        String filePath = "/storage/fetch";
        // 最后的存储路径
        String relativePath = filePath + "/" + fileName;
        // 存储文件
        File file = new File(docBase + relativePath);
        if(!file.getParentFile().exists()){
            //如果父级目录不存在，则我们创建所有的父级目录
            file.getParentFile().mkdirs();
        }
        // 文件写入
        part.write(file.getAbsolutePath());
        // 获取ip
        String ip = request.getRequestURL().toString().replace("/admin/storage/create", "");
        // 创建对象存储对象
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(fileName);
        marketStorage.setName(part.getSubmittedFileName());
        marketStorage.setType(part.getContentType());
        marketStorage.setSize((int) part.getSize());
        marketStorage.setUrl(ip + relativePath);
        marketStorage.setAddTime(LocalDateTime.now());
        marketStorage.setUpdateTime(LocalDateTime.now());
        // 对象存储的核心代码
        int flag = adminStorageService.create(marketStorage);
        // 判定结果
        if (flag != 1) {
            Object o = ResponseUtil.updatedDataFailed();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
            return;
        }
        Object ok = ResponseUtil.ok(marketStorage);

        response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
        return;
    }

    /**
     * 存储对象查询方法
     * @param request 请求
     * @param response 响应
     */
    @GetMapping("/list")
    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取各参数数据
        Integer page = Integer.parseInt(request.getParameter("page"));
        Integer limit = Integer.parseInt(request.getParameter("limit"));
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");
        String key = request.getParameter("key");
        String name = request.getParameter("name");

        // TODO 完善性判定

        // 查询核心代码
        List<MarketStorage> adminList = adminStorageService.list(page, limit, sort, order, key, name);
        // 设置响应对象
        Object ok = ResponseUtil.okList(adminList);
        // 设置响应体
        response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    /**
     * 对象存储更新
     * @param request 请求
     * @param response 响应
     */
    @PostMapping("/update")
    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取Post请求体
        String requestBody = ZhouWenUtil.getRequestBody(request);
        // 数据转对象
        MarketStorage updateMarketStorage = JacksonUtil.getObjectMapper().readValue(requestBody, MarketStorage.class);
        // TODO 数据规则性判断

        // 修改对象存储的核心操作
        MarketStorage marketStorage = adminStorageService.update(updateMarketStorage);
        // 判定
        if (marketStorage == null) {
            Object serious = ResponseUtil.serious();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(serious));
        }
        // 响应
        Object ok = ResponseUtil.ok(marketStorage);
        response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    /**
     * 对象存储删除
     * @param request 请求
     * @param response 响应
     */
    @PostMapping("/delete")
    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取Post请求体
        String requestBody = ZhouWenUtil.getRequestBody(request);
        // 数据转对象
        MarketStorage marketStorage = JacksonUtil.getObjectMapper().readValue(requestBody, MarketStorage.class);
        // TODO 数据完善性判断

        // 删除对象存储的核心操作
        boolean result = adminStorageService.delete(marketStorage);
        // 判定操作结果
        if (result) {
            // 响应
            Object ok = ResponseUtil.ok();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
        } else {
            // 响应
            Object o = ResponseUtil.updatedDataFailed();
            response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
        }
    }
}